#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <pthread.h>

#define PORT 8080
#define BUFFER_SIZE 1024

int client_fd = -1; // 客户端连接的文件描述符

// 线程处理从客户端接收消息
void* receive_messages(void* arg) {
    char buffer[BUFFER_SIZE];
    int bytes_read;

    while (1) {
        if (client_fd == -1) {
            sleep(1);
            continue;
        }

        bytes_read = read(client_fd, buffer, sizeof(buffer)); // 接收客户端消息
        if (bytes_read > 0) {
            buffer[bytes_read] = '\0'; // 确保字符串结束
            printf("Received from client: %s\n", buffer);
            
            // 如果收到 -1，关闭连接
            if (strcmp(buffer, "-1") == 0) {
                printf("Received '-1'. Closing connection.\n");
                close(client_fd);
                client_fd = -1;
                break;
            }
        }
    }

    return NULL;
}

int main() {
    int server_fd;
    struct sockaddr_in server_addr, client_addr;
    socklen_t addr_len;
    char buffer[BUFFER_SIZE];
    pthread_t receiver_thread;

    // 创建 socket
    if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
        perror("socket failed");
        exit(EXIT_FAILURE);
    }

    // 配置服务器地址
    server_addr.sin_family = AF_INET;
    server_addr.sin_addr.s_addr = INADDR_ANY; // 任意IP地址
    server_addr.sin_port = htons(PORT);

    // 绑定地址到 socket
    if (bind(server_fd, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0) {
        perror("bind failed");
        close(server_fd);
        exit(EXIT_FAILURE);
    }

    // 监听端口
    if (listen(server_fd, 3) < 0) {
        perror("listen failed");
        close(server_fd);
        exit(EXIT_FAILURE);
    }

    printf("Server listening on port %d...\n", PORT);

    addr_len = sizeof(client_addr);
    
    // 接受客户端连接
    if ((client_fd = accept(server_fd, (struct sockaddr *)&client_addr, &addr_len)) < 0) {
        perror("accept failed");
        close(server_fd);
        exit(EXIT_FAILURE);
    }

    printf("Client connected: %s\n", inet_ntoa(client_addr.sin_addr));

    // 创建接收消息线程
    if (pthread_create(&receiver_thread, NULL, receive_messages, NULL) != 0) {
        perror("Thread creation failed");
        close(client_fd);
        close(server_fd);
        exit(EXIT_FAILURE);
    }

    // 允许服务器端手动输入消息并发送
    while (1) {
        printf("Enter message to send to client (or type '-1' to quit): ");
        fgets(buffer, sizeof(buffer), stdin);
        buffer[strcspn(buffer, "\n")] = '\0';  // 去掉换行符

        // 如果输入 -1，退出服务器
        if (strcmp(buffer, "-1") == 0) {
            break;
        }

        // 发送消息到客户端
        if (client_fd != -1) {
            send(client_fd, buffer, strlen(buffer), 0);
            printf("Sent to client: %s\n", buffer);
        } else {
            printf("No client connected.\n");
        }
    }

    // 清理资源
    pthread_join(receiver_thread, NULL);
    close(client_fd);
    close(server_fd);
    
    return 0;
}
